#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]

use std::fs;
use std::path::Path;
use docx_rs::*;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct ConversionResult {
    success: bool,
    message: String,
}

#[tauri::command]
async fn convert_to_markdown(input_path: String, output_path: String) -> Result<ConversionResult, String> {
    let input_file = Path::new(&input_path);
    let output_file = Path::new(&output_path)
        .join(input_file.file_stem().unwrap())
        .with_extension("md");

    match fs::read(&input_path) {
        Ok(content) => {
            match read_docx(&content) {
                Ok(doc) => {
                    let markdown = convert_docx_to_markdown(&doc);
                    match fs::write(&output_file, markdown) {
                        Ok(_) => Ok(ConversionResult {
                            success: true,
                            message: "转换成功".to_string(),
                        }),
                        Err(e) => Ok(ConversionResult {
                            success: false,
                            message: format!("写入文件失败: {}", e),
                        })
                    }
                },
                Err(e) => Ok(ConversionResult {
                    success: false,
                    message: format!("解析Word文档失败: {}", e),
                })
            }
        },
        Err(e) => Ok(ConversionResult {
            success: false,
            message: format!("读取文件失败: {}", e),
        })
    }
}

fn convert_docx_to_markdown(doc: &Docx) -> String {
    // 这里实现具体的转换逻辑
    // 可以使用 docx-rs 库提供的方法来解析文档结构
    // 将文档内容转换为 Markdown 格式
    let mut markdown = String::new();
    
    // 示例转换逻辑
    for paragraph in doc.paragraphs() {
        for run in paragraph.runs() {
            markdown.push_str(&run.text());
        }
        markdown.push_str("\n\n");
    }
    
    markdown
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![convert_to_markdown])
        .run(tauri::generate_context!())
        .expect("运行应用失败");
} 